package com.ruoyi.web.sso.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.ruoyi.common.core.text.Convert;
import com.ruoyi.web.sso.common.util.AssertUtil;
import com.ruoyi.web.sso.domain.*;
import com.ruoyi.web.sso.domain.DTO.AreaSettingDTO;
import com.ruoyi.web.sso.domain.vo.AreaVO;
import com.ruoyi.web.sso.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 园所信息Controller
 * 
 * @author ruoyi
 * @date 2021-11-03
 */
@Controller
@RequestMapping("/sso/area")
@Api(tags = "园所信息")
public class AreaController extends BaseController
{
    private String prefix = "sso/area";

    @Autowired
    private IAreaService areaService;

    @Autowired
    private IGroupService groupService;

    @Autowired
    private IAreaStaffService areaStaffService;

    @Autowired
    private IPlatformService platformService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IStaffService staffService;

    @Autowired
    private IDictDataService dictDataService;

    String LIVEROOM_SWITCH_KEY = "LIVEROOM_SWITCH_KEY";

    String LIVE_ROOM_SWITCH_KEY = "LIVE_ROOM_SWITCH_KEY";

    String MILEPOST_ITEM = "milepost_item";
    @GetMapping()
    @ApiOperation(value="查询列表页面",notes="查询列表页面")
    public String area(String groupId, ModelMap mmap)
    {
        mmap.put("groupId", groupId);
        return prefix + "/area";
    }

    /**
     * 查询园所信息列表
     */
    @RequiresPermissions("sso:area:list")
    @PostMapping("/list")
    @ResponseBody
    @ApiOperation(value="查询列表",notes="查询页面")
    public TableDataInfo list(Area area)
    {
        startPage();
        area.setDeleted(0);
        List<AreaVO> list = areaService.selectAreaList(area);
        return getDataTable(list);
    }

    /**
     * 导出园所信息列表
     */
    @RequiresPermissions("sso:area:export")
    @Log(title = "园所信息", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    @ApiOperation(value="导出园所信息列表",notes="导出园所信息列表")
    public AjaxResult export(Area area)
    {
        List<AreaVO> list = areaService.selectAreaList(area);
        ExcelUtil<AreaVO> util = new ExcelUtil<AreaVO>(AreaVO.class);
        return util.exportExcel(list, "园所信息数据");
    }

    /**
     * 新增园所信息
     */
    @GetMapping("/add")
    @ApiOperation(value="新增园所信息页面跳转",notes="新增园所信息页面跳转")
    public String add(ModelMap mmap)
    {
        List<Group> list = groupService.selectGroupList(new Group());
        mmap.put("groupList", list);
        return prefix + "/add";
    }

    /**
     * 新增保存园所信息
     */
    @RequiresPermissions("sso:area:add")
    @Log(title = "园所信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    @ApiOperation(value="新增园所信息",notes="新增园所信息")
    public AjaxResult addSave(Area area)
    {
        return toAjax(areaService.insertArea(area));
    }


    /**
     * 修改园所信息
     */
    @GetMapping("/edit/{id}")
    @ApiOperation(value="修改园所信息页面跳转",notes="修改园所信息页面跳转")
    public String edit(@PathVariable("id") String id, ModelMap mmap)
    {
        AreaVO area = areaService.selectAreaById(id);
        Map<String, Object> params = new HashMap<>();
        //摄像总开关
        AreaSettingDTO settingDTO = dictDataService.selectKeyAndByAreaIdDictData(LIVEROOM_SWITCH_KEY,MILEPOST_ITEM,id);
        //签到开摄像
        AreaSettingDTO settingDTO1 = dictDataService.selectKeyAndByAreaIdDictData(LIVE_ROOM_SWITCH_KEY,MILEPOST_ITEM,id);
        int totalSwitch = 0;
        int signSwitch = 0;
        if (AssertUtil.isNotEmpty(settingDTO)){
           if (StringUtils.equals("true",settingDTO.getValue())){
               totalSwitch = 1;
           }
        }

        if (AssertUtil.isNotEmpty(settingDTO1)){
            if (StringUtils.equals("1",settingDTO1.getValue())){
                signSwitch = 1;
            }
        }
        //摄像总开关
        params.put("totalSwitch", totalSwitch);
        //签到开摄像
        params.put("signSwitch",signSwitch);
        area.setParams(params);
        mmap.put("area", area);
        List<Group> list = groupService.selectGroupList(new Group());
        mmap.put("groupList", list);
        return prefix + "/edit";
    }

    /**
     * 修改保存园所信息
     */
    @Log(title = "园所信息", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    @ApiOperation(value="修改园所信息",notes="修改园所信息")
    public AjaxResult editSave(Area area)
    {
        if (AssertUtil.isNotEmpty(area.getParams().get("totalSwitch"))){
            String v = (String) area.getParams().get("totalSwitch");
            if (StringUtils.equals(v,"1")){
                v = "true";
            }
            //摄像总开关
            AreaSettingDTO settingDTO = dictDataService.selectKeyAndByAreaIdDictData(LIVEROOM_SWITCH_KEY,MILEPOST_ITEM,area.getId());
            if (AssertUtil.isNotEmpty(settingDTO)){
                if (!StringUtils.equals( v,settingDTO.getValue())){
                    DictData dictData = dictDataService.selectDictDataByDictCode(settingDTO.getId());
                    dictData.setDictValue(v);
                    dictDataService.updateDictData(dictData);
                }
            }else {
                DictData dictData = new DictData();
                dictData.setAreaId(area.getId());
                dictData.setDictLabel(LIVEROOM_SWITCH_KEY);
                dictData.setDictType(MILEPOST_ITEM);
                dictData.setDictValue(v);
                dictData.setRemark("幼儿园摄像头开关");
                dictDataService.insertDictData(dictData);
            }
        }
        //签到开摄像
        if (AssertUtil.isNotEmpty(area.getParams().get("signSwitch"))){
            String v = (String) area.getParams().get("signSwitch");
            //摄像总开关
            AreaSettingDTO settingDTO = dictDataService.selectKeyAndByAreaIdDictData(LIVE_ROOM_SWITCH_KEY,MILEPOST_ITEM,area.getId());
            if (AssertUtil.isNotEmpty(settingDTO)){
                if (!StringUtils.equals( v,settingDTO.getValue())){
                    DictData dictData = dictDataService.selectDictDataByDictCode(settingDTO.getId());
                    dictData.setDictValue(v);
                    dictDataService.updateDictData(dictData);
                }
            }else {
                DictData dictData = new DictData();
                dictData.setAreaId(area.getId());
                dictData.setDictLabel(LIVE_ROOM_SWITCH_KEY);
                dictData.setDictType(MILEPOST_ITEM);
                dictData.setDictValue(v);
                dictData.setRemark("幼儿园摄像头开关");
                dictDataService.insertDictData(dictData);
            }
        }
        return toAjax(areaService.updateArea(area));
    }

    @Log(title = "重置园所角色", businessType = BusinessType.UPDATE)
    @PostMapping( "/resetRoleList")
    @ResponseBody
    @ApiOperation(value="重置园所角色",notes="重置园所角色")
    public AjaxResult resetRoleList(String areaId)
    {
        return toAjax(areaService.resetAreaRoleList(areaId));
    }


    /**
     * 删除园所信息
     */
    @Log(title = "园所信息", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    @ApiOperation(value="删除园所信息",notes="删除园所信息")
    public AjaxResult remove(String ids)
    {
        return toAjax(areaService.deleteAreaByIds(ids));
    }

    /**
     * 查询分配园区用户
     */
    @GetMapping("/authUser/{id}")
    @ApiOperation(value="查询分配园区用户",notes="查询分配园区用户")
    public String authUser(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("areaId", id);
        return  "sso/area/authUser";
    }

    /**
     * 查询分配园区用户
     */
    @GetMapping("/areaUser")
    @ApiOperation(value="查询分配园区用户",notes="查询分配园区用户")
    public String areaUser(String roleId, ModelMap mmap)
    {
        mmap.put("role", roleService.selectRoleByRoleId(roleId));
        return  "sso/area/areaUser";
    }

    @GetMapping("/selectAreaUser")
    @ApiOperation(value="分配用户页面",notes="分配用户页面")
    public String selectAreaUser( String roleId, ModelMap mmap)
    {
        mmap.put("role", roleService.selectRoleByRoleId(roleId));
        return   "sso/area/selectAreaUser";
    }


    /**
     * 分配用户
     */
    @GetMapping("/addStaff")
    @ApiOperation(value="查询分配园区用户",notes="查询分配园区用户")
    public String Area( String areaId, ModelMap mmap)
    {
        mmap.put("areaId", areaId);
        return prefix + "/addStaff";
    }

    /**
     * 添加分配用户
     */
    @PostMapping("/addStaff")
    @ResponseBody
    @ApiOperation(value="添加分配用户",notes="添加分配用户")
    public AjaxResult addStaff( String areaId,String[] staffIds)
    {
        for (int i = 0; i <staffIds.length ; i++) {
            areaService.addStaff(areaId,staffIds[i]);
        }
        return AjaxResult.success("成功");
    }

    /**
     * 删除用户权限
     * @return
     */
    @PostMapping("/cancelStaffArea")
    @ResponseBody
    @ApiOperation(value="删除用户权限",notes="删除用户权限")
    public AjaxResult deleteStaffRoleInfo(String areaId, String staffId)
    {
        return areaStaffService.deleteStaffAreaInfo(areaId,staffId );
    }

    /**
     * 设为默认
     * @return
     */
    @PostMapping("/setAreaDefault")
    @ResponseBody
    @ApiOperation(value="设为默认",notes="设为默认")
    public AjaxResult setAreaDefault(String areaId, String staffId)
    {
        return areaStaffService.setAreaDefault(areaId,staffId );
    }


    /**
     * 批量删除用户权限
     * @return
     */
    @PostMapping("/cancelStaffAreas")
    @ResponseBody
    @ApiOperation(value="批量删除用户权限",notes="批量删除用户权限")
    public AjaxResult cancelStaffAreas(String areaId, String staffIds)
    {
        return areaStaffService.deleteStaffAreaInfos(areaId, Convert.toStrArray(staffIds));
    }


    /**
     * 园区角色列表页面
     */
    @GetMapping("/areaByRoleList/{id}")
    @ApiOperation(value="园区角色列表页面",notes="园区角色列表页面")
    public String areaByRoleListHtml(@PathVariable("id") String id, ModelMap mmap)
    {
        mmap.put("id", id);
        return prefix + "/areaByRoleList";
    }


    /**
     * 园区角色列表
     */
    @PostMapping("/areaByRoleList")
    @ResponseBody
    @ApiOperation(value="园区角色列表",notes="园区角色列表")
    public TableDataInfo areaByRoleList( String id,  String roleName)
    {
        startPage();
        List<Map<String,Object>> list= areaService.areaByRoleList(id,roleName);
        return getDataTable(list);

    }

    /**
     * 园区新增角色
     */
    @GetMapping("/addRole/{id}")
    @ApiOperation(value="园区角色列表页面",notes="园区角色列表页面")
    public String addRole(@PathVariable("id") String id, ModelMap mmap)
    {
        List<Platform> platforms = platformService.selectPlatformList(new Platform());
        mmap.put("platforms", platforms);
        mmap.put("id", id);
        return prefix + "/addRole";
    }

    @PostMapping("/selectAreaUnallocatedList")
    @ResponseBody
    @ApiOperation(value="查询园区未分配用户信息列表",notes="查询园区未分配用户信息列表")
    public TableDataInfo selectAreaUnallocatedList(@ApiParam(value = "角色ID")@RequestParam(required=false) String roleId,
                                                   @ApiParam(value = "园区ID")@RequestParam(required=false) String areaId,
                                               @ApiParam(value = "账号")@RequestParam(required=false) String mobile)
    {
        Map<String,Object> map = new HashMap<>();
        map.put("roleId",roleId);
        map.put("areaId",areaId);
        map.put("mobile",mobile);
        startPage();
        List<Staff> list = staffService.selectAreaUnallocatedList(map);
        return getDataTable(list);
    }
}
